﻿#region USINGS
using System;
using System.Data;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using DevComponents.DotNetBar.Controls;
using PolePositionDesktop.WebService;
using GoogleEarthClasses.Entities;
using GoogleEarthClasses.Global;
using GoogleEarthClasses.Logic;
using System.Configuration;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Net;
#endregion USINGS

namespace PolePositionDesktop
{
    public partial class AssetForm : Form
    {
        #region Local variables
        ActionType m_ActionType;
        EPoint m_Asset;
        bool m_ActionCompleted;
        string m_SDFDatabaseFolder;
        Modes m_Mode;
        public string[] m_Colors;
        #endregion Local variables
        #region PROPERTIES
        public ActionType ActionType
        {
            set { 
                m_ActionType = value;
                EnableFields();
            }
        }
        public EPoint Asset
        {
            set { m_Asset = value; }
            get { return m_Asset; }
        }
        public bool ActionCompleted
        {
            set{m_ActionCompleted = value;}
            get{return m_ActionCompleted;}
        }
        public Modes Mode
        {
            set{m_Mode = value;}
            get{return m_Mode;}
        }
        public string SDFDatabaseFolder
        {
            set{m_SDFDatabaseFolder = value;}
            get{return m_SDFDatabaseFolder;}
        }
        public string[] Colors
        {
            set { m_Colors = value; }
            get { return m_Colors; }
        }
        #endregion PROPERTIES

        #region FORM EVENTS AND BUTTONS
        public AssetForm()
        {
            InitializeComponent();
        }
        private void AssetForm_Load(object sender, EventArgs e)
        {
            LoadColors();
            LoadAssetData();
            LoadTitle();
        }
        private void LoadTitle() { 
            string m_Message = "";
            switch(m_ActionType){
                case ActionType.Delete:
                    m_Message = "Remove asset " + m_Asset.LocationId.ToString();
                    break;
                case ActionType.New:
                    m_Message = "Create new asset ";
                    break;
                case ActionType.Edit: 
                    m_Message = "Edit asset " + m_Asset.LocationId.ToString();
                    break;
            }
            lblTitle.Text = m_Message;
        }
        private void buttonAccept_Click(object sender, EventArgs e)
        {
            string _ActionCompleted="";
            switch (m_ActionType) { 
                case ActionType.New:
                    NewAsset();
                    _ActionCompleted = "The asset has been created successfully";
                    break;
                case ActionType.Edit:
                    EditAsset();
                    _ActionCompleted = "The asset has been edited successfully";
                    break;
                case ActionType.Delete:
                    DeleteAsset();
                    _ActionCompleted = "The asset has been deleted successfully";
                    break;
            }
            MessageBox.Show(_ActionCompleted);
            m_ActionCompleted = true;
            this.Close();
        }
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            m_ActionCompleted = false;
            this.Close();
        }
        private void AssetForm_Resize(object sender, EventArgs e)
        {
            this.panelViewLocalPhotos.Size = new Size(this.panelViewLocalPhotos.Size.Width, panelViewLocalPhotos.Height);
        }
        private PictureBox FindControlByName(string name)
        {
            foreach (Control _Control in panelViewLocalPhotos.Controls) //assuming this is a Form
            {
                if (_Control.Name == name)
                    return (PictureBox) _Control; //found
            }
            return null; //not found
        }

        #endregion FORM EVENTS AND BUTTONS
        #region LOAD INFORMATION
        private void EnableFields()
        {
            if (m_ActionType == ActionType.Delete)
            {
                LabelAltitude.Enabled = false;
                LabelLatitude.Enabled = false;
                LabelLongitude.Enabled = false;
                DropDownColors.Enabled = false;
                txtDescription.Enabled = false;
                txtSatellites.Enabled = false;
                txtAngle.Enabled = false;
                buttonClearImage0.Enabled = false;
                buttonClearImage1.Enabled = false;
                buttonClearImage2.Enabled = false;
                buttonClearImage3.Enabled = false;
                buttonSelectImage0.Enabled = false;
                buttonSelectImage1.Enabled = false;
                buttonSelectImage2.Enabled = false;
                buttonSelectImage3.Enabled = false;
            }
        }
        private void LoadAssetData()
        {
            LabelAltitude.Text = m_Asset.Altitude.ToString();
            LabelLatitude.Text = m_Asset.Latitude.ToString();
            LabelLongitude.Text = m_Asset.Longitude.ToString();
            if (!String.IsNullOrEmpty(m_Asset.Color))
                DropDownColors.SelectedItem = m_Asset.Color;
            else
                DropDownColors.SelectedIndex = 0;
            txtDescription.Text = m_Asset.Description;
            txtSatellites.Text = m_Asset.Satellites.ToString();
            txtAngle.Text = m_Asset.Angle.ToString();
            if (m_ActionType!= ActionType.New) 
                LoadLocalImagesInPanel();
        }
        private void LoadColors()
        {
            foreach (string _color in m_Colors)
            {
                DropDownColors.Items.Add((object)_color);
            }
        } 
        #endregion LOAD INFORMATION

        #region ASSETS NEW, EDIT REMOVE
        private void EditAsset()
        {
            try
            {
                m_Asset.Altitude = double.Parse(LabelAltitude.Text);
                m_Asset.Latitude = double.Parse(LabelLatitude.Text);
                m_Asset.Longitude = double.Parse(LabelLongitude.Text);
                m_Asset.Color = DropDownColors.SelectedItem.ToString();
                m_Asset.Description = txtDescription.Text;
                m_Asset.Satellites = int.Parse(txtSatellites.Text);
                m_Asset.Angle = double.Parse(txtAngle.Text);
                if (m_Mode == Modes.Local)
                {
                    LocateDatabases _LocateDatabases = new LocateDatabases();
                    _LocateDatabases.SDFDatabasesPath = DirHelper.GetSdfPath(m_SDFDatabaseFolder);
                    _LocateDatabases.UpdatePositionDataById(m_Asset.LocationId, 
                                                        m_Asset.Longitude, 
                                                        m_Asset.Latitude, 
                                                        m_Asset.Altitude, 
                                                        m_Asset.Color);
                    UpdateImagesList();
                    _LocateDatabases.UpdatePositionAmountImages(m_Asset.LocationId, m_Asset.HaveImages);
                }
                else
                {
                    Service1 WebServer = new Service1();
                    WebServer.PositionUpdate(m_Asset.LocationId,
                                            m_Asset.Longitude,
                                            m_Asset.Latitude,
                                            m_Asset.Altitude,
                                            m_Asset.Description,
                                            m_Asset.SatelliteTime,
                                            m_Asset.Satellites,
                                            m_Asset.Angle,
                                            m_Asset.Color);
                    UpdateImagesList();

                }
            }
            catch (FormatException ex)
            {
                MessageBox.Show(Constants.k_FormatIncorret + "\n" + ex.Message);
            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("buttonSaveChanges_Click->\n" + ex.Message + "\n" + ex.StackTrace);
            }
        }
        private void NewAsset()
        {
            m_Asset.Altitude = double.Parse(LabelAltitude.Text);
            m_Asset.Latitude = double.Parse(LabelLatitude.Text);
            m_Asset.Longitude = double.Parse(LabelLongitude.Text);
            m_Asset.Color = DropDownColors.SelectedItem.ToString();
            m_Asset.Description = txtDescription.Text;
            m_Asset.SatelliteTime = DateTime.Now;
            m_Asset.Satellites = int.Parse(txtSatellites.Text);
            m_Asset.Angle = double.Parse(txtAngle.Text);
            Service1 Webserver = new Service1();
            m_Asset.LocationId = Webserver.PositionInsert(
                                        m_Asset.Longitude,
                                        m_Asset.Latitude,
                                        m_Asset.Altitude,
                                        m_Asset.Description,
                                        m_Asset.SatelliteTime,
                                        m_Asset.Satellites,
                                        m_Asset.Angle,
                                        m_Asset.Color);
            UpdateImagesList();
        }
        private void DeleteAsset()
        {
            if (m_Mode == Modes.Local)
            {
                LocateDatabases _LocateDatabases = new LocateDatabases();
                _LocateDatabases.SDFDatabasesPath = DirHelper.GetSdfPath(m_SDFDatabaseFolder);
                _LocateDatabases.DeletePositionDataById(m_Asset.LocationId);
            }
            else
            {
                Service1 WebServer = new Service1();
                WebServer.PositionDelete(m_Asset.LocationId);
            }
        }
        private void UpdateImagesList()
        {
            PictureBox _PhotoPreview;
            List<EImage> _UpdatedImages = new List<EImage>();
            EImage _ImageTemp;
            for (int _Counter = 0; _Counter < 4; _Counter++)
            {
                _PhotoPreview = FindControlByName("PhotoPreview" + (_Counter).ToString());
                if (UpdateAssetImage(_Counter, _PhotoPreview.ImageLocation, _PhotoPreview.Image))
                {
                    if (m_Mode == Modes.Server)
                        _ImageTemp = new EImage(UpdateLocalImageAndUploadAssetImagesToServer(_Counter, _PhotoPreview));
                    else
                        _ImageTemp = new EImage(UpdateLocalImageAndCopyAssetImagesToOutboxFolder(_Counter, _PhotoPreview));

                    if (_ImageTemp.ImageId != 0)
                        _UpdatedImages.Add(_ImageTemp);
                }
                else
                {
                    if (m_Asset.Images[_Counter].ContentPath == _PhotoPreview.ImageLocation)
                    {
                        _UpdatedImages.Add(m_Asset.Images[_Counter]);
                    }
                }
            }
            m_Asset.Images = _UpdatedImages;
            m_Asset.HaveImages = m_Asset.Images.Count;
        }
        private bool UpdateAssetImage(int ImageNumber, string ImageLocation, Image Image)
        {
            if (ImageLocation != null)
            {
                if (m_Asset.Images.Count > ImageNumber)
                {
                    if (m_Asset.Images[ImageNumber] != null)
                    {
                        if (m_Asset.Images[ImageNumber].ContentPath == ImageLocation && Image != null)
                        {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        
        /// <summary>
        ///THIS METHOD UPLOADS THE NEW IMAGES TO THE SERVER AND COPIES THE THUMBNAILS TO IMAGE-CACHE
        ///ONLY FOR SERVER MODE!!!
        /// </summary>
        /// <returns>IF 0, THE IMAGE HAS BEEN DELETED. IF>0 RETURNS ID IMAGE FROM SERVER</returns>
        private int UpdateLocalImageAndUploadAssetImagesToServer(int ImageNumber, PictureBox PictureBox)
        {
            Service1 Webserver = new Service1();
            Int32 _ImageId = 0;
            if (m_ActionType == ActionType.Edit)
            {
                if (m_Asset.Images.Count > ImageNumber)
                {  //THERE IS AN EXISTING IMAGE ALREADY, AND NEEDS TO BE DELETED
                    try
                    {
                        File.Delete(m_Asset.Images[ImageNumber].ContentPath);
                    }
                    catch { }

                    Webserver.PositionImageDelete(m_Asset.Images[ImageNumber].ImageId);
                }
            }
            if (PictureBox.Image != null)
            {
                //UNLOAD THE PICTURE FROM THE PICTURE  BOX
                string _NewImagePath;
                _NewImagePath = PictureBox.ImageLocation;
                PictureBox.Image = null;
                //LOAD THE PICTURE FROM THE PICTURE  BOX, CONVERT IT TO BYTE ARRAY AND UPLOAD TO SERVER
                Image _Image = Image.FromFile(_NewImagePath);
                lblTitle.Text = "Uploading image " + _NewImagePath;
                _ImageId = Webserver.PositionImageInsert(m_Asset.LocationId, ImageNumber.ToString(), GImages.ConvertImageToByteArray(_Image, System.Drawing.Imaging.ImageFormat.Jpeg));
                LoadTitle();
            }
            return _ImageId;
        }

        //THIS METHOD COPIES THE NEW IMAGES TO THE OUTBOX FOLDER --> ONLY FOR LOCAL MODE!!!
        private int UpdateLocalImageAndCopyAssetImagesToOutboxFolder(int ImageNumber, PictureBox PictureBox)
        {
            Int32 _ImageId = 0;

            #region DELETE EXISTING IMAGE
            if (m_ActionType == ActionType.Edit)
            {
                if (m_Asset.Images.Count > ImageNumber)
                {  //THERE IS AN EXISTING IMAGE ALREADY, AND NEEDS TO BE DELETED
                    try
                    {
                        File.Delete(m_Asset.Images[ImageNumber].ContentPath);
                    }
                    catch { }
                }
            }
            #endregion DELETE EXISTING IMAGE
            if (PictureBox.Image != null)
            {
                //UNLOAD THE PICTURE FROM THE PICTURE  BOX
                string _DestinationImagePath;
                string _NewImagePath;
                _NewImagePath = PictureBox.ImageLocation;
                PictureBox.Image = null;
                //COPY THE FILE TO THE "OUTBOX\FOLDER ID \IMAGES FOLDER"
                _DestinationImagePath = m_SDFDatabaseFolder + "//"+Constants.K_DirImagesName + "//";
                _DestinationImagePath += m_Asset.LocationId.ToString() + "_" + ImageNumber.ToString() + Constants.K_ImagesExtension;
                File.Copy(_NewImagePath, _DestinationImagePath,true);
                _ImageId = ImageNumber;
            }
            return _ImageId;
        }
        
        
        
        #endregion ASSETS NEW, EDIT REMOVE

        #region PHOTOS
        protected void LoadLocalImagesInPanel()
        {
            Int32 ImageCounter;
            List<EImage> ListEimages = m_Asset.Images;
            CleanPhotosPanel(); //Before include Picture box in panel, clear them
            for (ImageCounter =0; ImageCounter<ListEimages.Count;ImageCounter++) {
                if (!String.IsNullOrEmpty(ListEimages[ImageCounter].ContentPath)) {
                    ChangePicture(ImageCounter, ListEimages[ImageCounter].ContentPath);
                }
            }
        }
        private void ChangePicture(int PictureBoxNumber, string ImagePath)
        {
            PictureBox _PhotoPreview;
            _PhotoPreview = FindControlByName("PhotoPreview" + (PictureBoxNumber).ToString());
            ClearImage(PictureBoxNumber);
            _PhotoPreview.Load(ImagePath);
        }
        private void CleanPhotosPanel()
        {
            PhotoPreview0.Image = null;
            PhotoPreview1.Image = null;
            PhotoPreview2.Image = null;
            PhotoPreview3.Image = null;
        }
        private void buttonSelectImage0_Click(object sender, EventArgs e)
        {
            SelectImage(0);
        }
        private void buttonSelectImage1_Click(object sender, EventArgs e)
        {
            SelectImage(1);
        }
        private void buttonSelectImage2_Click(object sender, EventArgs e)
        {
            SelectImage(2);
        }
        private void buttonSelectImage3_Click(object sender, EventArgs e)
        {
            SelectImage(3);
        }
        private void SelectImage(int PictureBoxNumber) {
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                ChangePicture(PictureBoxNumber,openDialog.FileName);
            }
        }
        #endregion
        #region  CLEAR IMAGES
        private void buttonClearImage0_Click(object sender, EventArgs e)
        {
            ClearImage(0);
        }
        private void buttonClearImage1_Click(object sender, EventArgs e)
        {
            ClearImage(1);
        }
        private void buttonClearImage2_Click(object sender, EventArgs e)
        {
            ClearImage(2);
        }
        private void buttonClearImage3_Click(object sender, EventArgs e)
        {
            ClearImage(3);
        }
        private void ClearImage(int PictureBoxNumber) {
            PictureBox _PhotoPreview;
            _PhotoPreview = FindControlByName("PhotoPreview" + (PictureBoxNumber).ToString());
            if (_PhotoPreview.Image != null) 
                _PhotoPreview.Image.Dispose();
            _PhotoPreview.Image = null;
            if (_PhotoPreview.InitialImage != null) 
                _PhotoPreview.InitialImage.Dispose();
            _PhotoPreview.InitialImage = null;
        }
        #endregion  CLEAR IMAGES



    }
}
